<?php

namespace plugin\admin\app\controller;

use app\service\YouYinService;
use support\Request;
use support\Response;
use plugin\admin\app\model\PhoneDn;
use plugin\admin\app\controller\Crud;
use support\exception\BusinessException;

/**
 * 分机绑定
 */
class PhoneDnController extends Crud
{

    /**
     * @var PhoneDn
     */
    protected $model = null;

    /**
     * 构造函数
     * @return void
     */
    public function __construct()
    {
        $this->model = new PhoneDn;
    }

    /**
     * 浏览
     * @return Response
     */
    public function index(): Response
    {
        return view('phone-dn/index');
    }

    /**
     * 插入
     * @param Request $request
     * @return Response
     * @throws BusinessException
     */
    public function insert(Request $request): Response
    {
        if ($request->method() === 'POST') {
            return parent::insert($request);
        }
        return view('phone-dn/insert');
    }

    /**
     * 更新
     * @param Request $request
     * @return Response
     * @throws BusinessException
     */
    public function update(Request $request): Response
    {
        if ($request->method() === 'POST') {
            return parent::update($request);
        }
        return view('phone-dn/update');
    }


    /**
     * 删除
     * @param Request $request
     * @return Response
     * @throws BusinessException
     */
    public function delete(Request $request): Response
    {
        $ids = $this->deleteInput($request);
        $this->doDelete($ids);
        return $this->json(0);
    }


    /**
     * 执行删除
     * @param array $ids
     * @return void
     */
    protected function doDelete(array $ids)
    {
        if (!$ids) {
            return;
        }
        $primary_key = $this->model->getKeyName();
        $this->model->whereIn($primary_key, $ids)->each(function ($model) {
          (new YouYinService())->unbind( $model->dn);
        });
    }

}
